package com.autobet.dao;

import com.autobet.model.table.Account;
import com.autobet.model.table.AutoHis;
import com.autobet.model.table.ResultHis;
import com.autobet.model.support.Visualization;
import com.autobet.services.EnvConfigService;
import com.autobet.utils.IdGenerator;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

/**
 * Created by yangd on 2017-08-27.
 */
@Repository
public class CommonDao {
    private static final Logger log = LoggerFactory.getLogger(CommonDao.class);
    @Autowired
    JdbcTemplate jdbcTemplate;

    public CommonDao() {
    }

    /**
     * 查询穿版次数
     * @param resultDate
     * @param buyNum
     * @return
     * @throws Exception
     */
    public BigDecimal queryMaxDieCountAutoHisByNum(String resultDate, String buyNum) throws Exception {
        try {
            StringBuffer sqlbuffer = new StringBuffer();
            sqlbuffer.append("select max(die_count) as diec from t_autohis where readly_flag = 'true' and  buydate_id in ( select buydate_id from t_result where result_date = ? ) and buy_num = ?");
            log.debug(sqlbuffer.toString());
            BigDecimal diecount = (BigDecimal)this.jdbcTemplate.queryForObject(sqlbuffer.toString(), new Object[]{resultDate, buyNum}, BigDecimal.class);
            return diecount;
        } catch (Exception var5) {
            log.error("查询最大穿版次数失败！", var5);
            throw new Exception("查询最大穿版次数失败！");
        }
    }

    /**
     * 查询穿版次数
     * @param resultDate
     * @return
     * @throws Exception
     */
    public BigDecimal queryMaxDieCountAutoHis(String resultDate) throws Exception {
        try {
            StringBuffer sqlbuffer = new StringBuffer();
            sqlbuffer.append("select max(die_count_readly) as diec from t_autohis where readly_flag = 'true' and buydate_id in ( select buydate_id from t_result where result_date = ? )");
            log.debug(sqlbuffer.toString());
            BigDecimal diecount = (BigDecimal)this.jdbcTemplate.queryForObject(sqlbuffer.toString(), new Object[]{resultDate}, BigDecimal.class);
            return diecount;
        } catch (Exception var4) {
            log.error("查询最大穿版次数失败！", var4);
            throw new Exception("查询最大穿版次数失败！");
        }
    }

    public List<AutoHis> queryAutoHisTop(String betType) throws Exception {
        try {
            StringBuffer sqlbuffer = new StringBuffer();
            sqlbuffer.append("select * from t_autohis where readly_flag = 'true'and buy_type = ? and buydate_id in ( SELECT top ").append(EnvConfigService.getQueryBuydateIdTop()).append(" distinct buydate_id FROM T_AUTOHIS order by buydate_id desc ) order by buydate_id desc");
            log.debug(sqlbuffer.toString());
            List<AutoHis> list = this.jdbcTemplate.query(sqlbuffer.toString(), new Object[]{betType}, new BeanPropertyRowMapper(AutoHis.class));
            return list;
        } catch (Exception var4) {
            log.error("queryAutoHisTop err!", var4);
            throw var4;
        }
    }

    public List<AutoHis>
    queryAutoHisByBuydateIdAndBetType(String buydateId, String betType) throws Exception {
        try {
            StringBuffer sqlbuffer = new StringBuffer();
            sqlbuffer.append("SELECT * FROM T_AUTOHIS WHERE BUYDATE_ID = ? AND BUY_TYPE = ?");
            log.debug(sqlbuffer.toString());
            List<AutoHis> list = this.jdbcTemplate.query(sqlbuffer.toString(), new Object[]{buydateId, betType}, new BeanPropertyRowMapper(AutoHis.class));
            return list;
        } catch (Exception var5) {
            log.error("queryAutoHisByBuydateId err!", var5);
            return null;
        }
    }

    /**
     * 获取最新一期数据
     * @return
     * @throws Exception
     */
    public List<AutoHis> getNewIDData() throws Exception {
        try {
            StringBuffer sqlbuffer = new StringBuffer();
            sqlbuffer.append("SELECT * FROM T_AUTOHIS  WHERE BUYDATE_ID = ( SELECT MAX(BUYDATE_ID) FROM T_AUTOHIS   )");
            log.debug(sqlbuffer.toString());
            List<AutoHis> list = this.jdbcTemplate.query(sqlbuffer.toString(), new BeanPropertyRowMapper(AutoHis.class));
            return list;
        } catch (Exception var5) {
            log.error("getNewIDData err!", var5);
            return null;
        }
    }

    /**
     * 获取最新单车数据
     * @return
     * @throws Exception
     */
    public AutoHis getNewIDDataOne( String type , String NO ) throws Exception {
        try {
            StringBuffer sqlbuffer = new StringBuffer();
            sqlbuffer.append("SELECT * FROM T_AUTOHIS  WHERE BUY_TYPE = ?  AND BUY_NUM = ? AND BUYDATE_ID = ( SELECT MAX(BUYDATE_ID) FROM T_AUTOHIS   )");
            log.debug(sqlbuffer.toString());
            AutoHis autoHis = (AutoHis)this.jdbcTemplate.queryForObject(sqlbuffer.toString(),new Object[]{type, NO}, new BeanPropertyRowMapper(AutoHis.class));
            return autoHis;
        } catch (Exception var5) {
            log.error("getNewIDDataOne err!", var5);
            return null;
        }
    }

    /**
     * 查询单车数据
     * @param type
     * @param NO
     * @return
     * @throws Exception
     */
    public AutoHis getDataOne( String type , String NO ,String ID) throws Exception {
        try {
            StringBuffer sqlbuffer = new StringBuffer();
            sqlbuffer.append("SELECT * FROM T_AUTOHIS  WHERE BUY_TYPE = ?  AND BUY_NUM = ? AND BUYDATE_ID = ? ");
            log.debug(sqlbuffer.toString());
            AutoHis autoHis = (AutoHis)this.jdbcTemplate.queryForObject(sqlbuffer.toString(),new Object[]{type, NO , ID }, new BeanPropertyRowMapper(AutoHis.class));
            return autoHis;
        } catch (Exception var5) {
            log.error("getDataOne err!", var5);
            return null;
        }
    }

    /**
     * 获取能统计盈亏的期数
     * @return
     * @throws Exception
     */
    public List<AutoHis> querySumTakeMoneyAutoHis() throws Exception {
        try {
            StringBuffer sqlbuffer = new StringBuffer();
            sqlbuffer.append("SELECT * FROM T_AUTOHIS WHERE LAST_BUYRESULT is not  NULL AND  LAST_BUYRESULT != '' AND sum_moneytake is null ");
            log.debug(sqlbuffer.toString());
            List<AutoHis> list = this.jdbcTemplate.query(sqlbuffer.toString(), new BeanPropertyRowMapper(AutoHis.class));
            return list;
        } catch (Exception var4) {
            log.error("querySumTakeMoneyAutoHis err!", var4);
            return null;
        }
    }

    public List<AutoHis> queryAutoHisByBuydateId(String buydateId) throws Exception {
        try {
            StringBuffer sqlbuffer = new StringBuffer();
            sqlbuffer.append("SELECT * FROM T_AUTOHIS WHERE readly_flag = 'true'and BUYDATE_ID = ? ");
            log.debug(sqlbuffer.toString());
            List<AutoHis> list = this.jdbcTemplate.query(sqlbuffer.toString(), new Object[]{buydateId}, new BeanPropertyRowMapper(AutoHis.class));
            return list;
        } catch (Exception var4) {
            log.error("queryAutoHisByBuydateId err!", var4);
            return null;
        }
    }

    public BigDecimal queryAutoHisBuymoneytakeAll(String betType) throws Exception {
        try {
            StringBuffer sqlbuffer = new StringBuffer();
            BigDecimal result;
            if("both".equals(betType)) {
                sqlbuffer.append("SELECT sum(buy_moneytake)  as mm FROM T_AUTOHIS where readly_flag = 'true' ");
                log.debug(sqlbuffer.toString());
                result = (BigDecimal)this.jdbcTemplate.queryForObject(sqlbuffer.toString(), BigDecimal.class);
            } else {
                sqlbuffer.append("SELECT sum(buy_moneytake)  as mm FROM T_AUTOHIS where readly_flag = 'true'and buy_type = ?");
                log.debug(sqlbuffer.toString());
                result = (BigDecimal)this.jdbcTemplate.queryForObject(sqlbuffer.toString(), new Object[]{betType}, BigDecimal.class);
            }

            return result == null?new BigDecimal("0"):result;
        } catch (Exception var4) {
            log.error("err!", var4);
            return new BigDecimal("0");
        }
    }

    public BigDecimal queryAutoHisBuymoneytakeRealAll(String betType) throws Exception {
        try {
            StringBuffer sqlbuffer = new StringBuffer();
            BigDecimal result;
            if("both".equals(betType)) {
                sqlbuffer.append("SELECT sum(buy_moneytake_readly) FROM T_AUTOHIS where readly_flag = 'true'and simulate_flag = ?");
                log.debug(sqlbuffer.toString());
                result = (BigDecimal)this.jdbcTemplate.queryForObject(sqlbuffer.toString(), new Object[]{"n"}, BigDecimal.class);
            } else {
                sqlbuffer.append("SELECT sum(buy_moneytake_readly) FROM T_AUTOHIS where readly_flag = 'true'and simulate_flag = ? and buy_type = ?");
                log.debug(sqlbuffer.toString());
                result = (BigDecimal)this.jdbcTemplate.queryForObject(sqlbuffer.toString(), new Object[]{"n", betType}, BigDecimal.class);
            }

            return result == null?new BigDecimal("0"):result;
        } catch (Exception var4) {
            log.error("err!", var4);
            return new BigDecimal("0");
        }
    }

    public BigDecimal queryAllAutoHisBuymoneytakeByResultDate(String resultDate, String betType) throws Exception {
        try {
            StringBuffer sqlbuffer = new StringBuffer();
            BigDecimal result;
            if("both".equals(betType)) {
                sqlbuffer.append("SELECT sum(buy_moneytake)  as mm FROM T_AUTOHIS where readly_flag = 'true'and buydate_id in (select buydate_id from t_result where result_date = ? ) ");
                log.debug(sqlbuffer.toString());
                result = (BigDecimal)this.jdbcTemplate.queryForObject(sqlbuffer.toString(), new Object[]{resultDate}, BigDecimal.class);
            } else {
                sqlbuffer.append("SELECT sum(buy_moneytake)  as mm FROM T_AUTOHIS where readly_flag = 'true'and buydate_id in (select buydate_id from t_result where result_date = ? ) and buy_type = ?");
                log.debug(sqlbuffer.toString());
                result = (BigDecimal)this.jdbcTemplate.queryForObject(sqlbuffer.toString(), new Object[]{resultDate, betType}, BigDecimal.class);
            }

            return result == null?new BigDecimal("0"):result;
        } catch (Exception var5) {
            log.error("err!", var5);
            return new BigDecimal("0");
        }
    }

    public BigDecimal queryRealAutoHisBuymoneytakeByResultDateAndSimulateFlag(String simulateFlag, String resultDate, String betType) throws Exception {
        try {
            StringBuffer sqlbuffer = new StringBuffer();
            BigDecimal result;
            if("both".equals(betType)) {
                sqlbuffer.append("SELECT sum(buy_moneytake_readly)  as mm FROM T_AUTOHIS where readly_flag = 'true'and simulate_flag = ? and buydate_id in (select buydate_id from t_result where result_date = ? )");
                log.debug(sqlbuffer.toString());
                result = (BigDecimal)this.jdbcTemplate.queryForObject(sqlbuffer.toString(), new Object[]{simulateFlag, resultDate}, BigDecimal.class);
            } else {
                sqlbuffer.append("SELECT sum(buy_moneytake_readly)  as mm FROM T_AUTOHIS where readly_flag = 'true' and simulate_flag = ? and buydate_id in (select buydate_id from t_result where result_date = ? ) and buy_type = ?");
                log.debug(sqlbuffer.toString());
                result = (BigDecimal)this.jdbcTemplate.queryForObject(sqlbuffer.toString(), new Object[]{simulateFlag, resultDate, betType}, BigDecimal.class);
            }

            return result == null?new BigDecimal("0"):result;
        } catch (Exception var6) {
            log.error("err!", var6);
            return new BigDecimal("0");
        }
    }

    public BigDecimal queryRealAutoHisBuymoneytakeByResultDate(String resultDate, String betType) throws Exception {
        try {
            StringBuffer sqlbuffer = new StringBuffer();
            BigDecimal result;
            if("both".equals(betType)) {
                sqlbuffer.append("SELECT sum(buy_moneytake_readly)  as mm FROM T_AUTOHIS where readly_flag = 'true' and buydate_id in (select buydate_id from t_result where result_date = ? )");
                log.debug(sqlbuffer.toString());
                result = (BigDecimal)this.jdbcTemplate.queryForObject(sqlbuffer.toString(), new Object[]{resultDate}, BigDecimal.class);
            } else {
                sqlbuffer.append("SELECT sum(buy_moneytake_readly)  as mm FROM T_AUTOHIS where readly_flag = 'true' and buydate_id in (select buydate_id from t_result where result_date = ? ) and buy_type = ?");
                log.debug(sqlbuffer.toString());
                result = (BigDecimal)this.jdbcTemplate.queryForObject(sqlbuffer.toString(), new Object[]{resultDate, betType}, BigDecimal.class);
            }

            return result == null?new BigDecimal("0"):result;
        } catch (Exception var5) {
            log.error("err!", var5);
            return new BigDecimal("0");
        }
    }

    /**
     * 盈亏统计
     * @param betType
     * @param betNum
     * @param buyDateID
     * @return
     * @throws Exception
     */
    public BigDecimal queryAutoHisBuymoneytakeSum(String betType,String betNum,String buyDateID) throws Exception {
        try {
            StringBuffer sqlbuffer = new StringBuffer();
            BigDecimal result;
            sqlbuffer.append("SELECT sum(buy_moneytake)  as mm FROM T_AUTOHIS where BUY_TYPE = ? AND BUY_NUM = ? AND BUYDATE_ID <= ? ");
            log.debug(sqlbuffer.toString());
            result = (BigDecimal)this.jdbcTemplate.queryForObject(sqlbuffer.toString(),new Object[]{ betType , betNum , buyDateID }, BigDecimal.class);

            return result == null?new BigDecimal("0"):result;
        } catch (Exception var4) {
            log.error("err!", var4);
            return null;
        }
    }

    public Account queryAccountByAccountId(String accountId) throws Exception {
        try {
            StringBuffer sqlbuffer = new StringBuffer();
            sqlbuffer.append("SELECT * FROM T_ACCOUNT WHERE ACCOUNT_ID = ?");
            log.debug(sqlbuffer.toString());
            Account account = (Account)this.jdbcTemplate.queryForObject(sqlbuffer.toString(), new Object[]{accountId}, new BeanPropertyRowMapper(Account.class));
            return account;
        } catch (Exception var4) {
            log.error("err!", var4);
            throw var4;
        }
    }

    public ResultHis queryResultHisByBuydateId(String buydateId) throws Exception {
        try {
            StringBuffer sqlbuffer = new StringBuffer();
            sqlbuffer.append("SELECT * FROM T_RESULT WHERE BUYDATE_ID = ?");
            log.debug(sqlbuffer.toString());
            ResultHis resultHis = (ResultHis)this.jdbcTemplate.queryForObject(sqlbuffer.toString(), new Object[]{buydateId}, new BeanPropertyRowMapper(ResultHis.class));
            return resultHis;
        } catch (Exception var4) {
            return null;
        }
    }

    /**
     * 查询符合条件的期数
     * @param buydateId1
     * @return
     * @throws Exception
     */
    public List<ResultHis> queryResultHisBySelectPeriod(String buydateId1,String buydateId2) throws Exception {
        try {
            StringBuffer sqlbuffer = new StringBuffer();
            sqlbuffer.append("SELECT  * FROM T_RESULT  where BUYDATE_ID <= ? and BUYDATE_ID >= ? order by BUYDATE_ID desc");
            log.debug(sqlbuffer.toString());
            List<ResultHis> resultHislist = this.jdbcTemplate.query(sqlbuffer.toString(), new Object[]{buydateId1,buydateId2}, new BeanPropertyRowMapper(ResultHis.class));
            return resultHislist;
        } catch (Exception var4) {
            return null;
        }
    }

    /**
     * 查询可选期数数量
     * @param buydateId
     * @return
     * @throws Exception
     */
    public List<ResultHis> queryResultHisBySelectFirst(String buydateId1,String buydateId2,String num) throws Exception {
        try {
            StringBuffer sqlbuffer = new StringBuffer();
            sqlbuffer.append("select * from (SELECT  * FROM T_RESULT  where BUYDATE_ID <= ? and BUYDATE_ID >= ? order by BUYDATE_ID desc) a where a.first_area like '%"+num+"%'");
            log.debug(sqlbuffer.toString());
            List<ResultHis> resultHislist = this.jdbcTemplate.query(sqlbuffer.toString(), new Object[]{buydateId1,buydateId2}, new BeanPropertyRowMapper(ResultHis.class));
            return resultHislist;
        } catch (Exception var4) {
            return null;
        }
    }

    /**
     * 查询可选期数数量
     * @param buydateId
     * @return
     * @throws Exception
     */
    public List<ResultHis> queryResultHisBySelectSecond(String buydateId1,String buydateId2,String num) throws Exception {
        try {
            StringBuffer sqlbuffer = new StringBuffer();
            sqlbuffer.append("select * from (SELECT  * FROM T_RESULT  where BUYDATE_ID <= ? and BUYDATE_ID >= ? order by BUYDATE_ID desc) a where a.second_area like '%"+num+"%'");
            log.debug(sqlbuffer.toString());
            List<ResultHis> resultHislist = this.jdbcTemplate.query(sqlbuffer.toString(), new Object[]{buydateId1,buydateId2}, new BeanPropertyRowMapper(ResultHis.class));
            return resultHislist;
        } catch (Exception var4) {
            return null;
        }
    }

    public ResultHis queryResultHisByResultDateAndFirst(String resultDate) throws Exception {
        try {
            StringBuffer sqlbuffer = new StringBuffer();
            sqlbuffer.append("SELECT * FROM T_RESULT WHERE RESULT_DATE = ? AND FIRST_FLAG = ? ");
            ResultHis resultHis = (ResultHis)this.jdbcTemplate.queryForObject(sqlbuffer.toString(), new Object[]{resultDate, "y"}, new BeanPropertyRowMapper(ResultHis.class));
            return resultHis;
        } catch (Exception var4) {
            return null;
        }
    }

    /**
     *  存入结果
     * @param autoHis
     * @throws Exception
     */
    public void saveAutoHis(AutoHis autoHis) throws Exception {
        try {
            autoHis.setDataId(IdGenerator.getSLId());
            autoHis.setInsertDate(new Date());
            StringBuffer sqlbuffer = new StringBuffer();
            sqlbuffer.append("INSERT INTO T_AUTOHIS(DATA_ID,ACCOUNT_ID,BUYDATE_ID,FIRST_FLAG,BUY_NUM,BUY_TYPE,BUY_AMOUNT,BUY_RESULT,BUY_MONEYTAKE,INSERT_DATE,BET_RULE,BUY_WHAT,BUY_RMONEYTAKE,curr_buyresult,last_buyresult,simulate_flag,pre_amount,die_count,readly_flag,buy_Amount_Readly,buy_MoneyTake_Readly,buy_What_Readly,buy_RMoneyTake_Readly,pre_Amount_Readly,die_count_readly) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
            log.info(sqlbuffer.toString());
            int var3 = this.jdbcTemplate.update(sqlbuffer.toString(), new Object[]{autoHis.getDataId(), autoHis.getAccountId(), autoHis.getBuydateId(), autoHis.getFirstFlag(), autoHis.getBuyNum(), autoHis.getBuyType(), autoHis.getBuyAmount(), autoHis.getBuyResult(), autoHis.getBuyMoneytake(), autoHis.getInsertDate(), autoHis.getBetRule(), autoHis.getBuyWhat(), autoHis.getBuyRMoneytake(), autoHis.getCurrBuyresult(),
                    autoHis.getLastBuyresult(), autoHis.getSimulateFlag(), autoHis.getPreAmount(), autoHis.getDieCount(),autoHis.getReadlyfalg(),autoHis.getBuyAmountReadly(),autoHis.getBuyMoneyTakeReadly(),autoHis.getBuyWhatReadly(),autoHis.getBuyRMoneyTakeReadly(),autoHis.getPreAmountReadly(),autoHis.getDieCountReadly()});
        } catch (Exception var4) {
            log.error("err!", var4);
            throw var4;
        }
    }

    /**
     * 保存结果list
     * @param autoHisList
     * @throws Exception
     */
    public void saveAutoHisList(List<AutoHis> autoHisList) throws Exception {
        try {
            Iterator var2 = autoHisList.iterator();

            while(var2.hasNext()) {
                AutoHis autoHis = (AutoHis)var2.next();

                //查询是否已经存在
//                AutoHis re = this.getDataOne( autoHis.getBuyType() , autoHis.getBuyNum() ,autoHis.getBuydateId());

//                if( re == null){
                    this.saveAutoHis(autoHis);
//                }else{
//                    this.updateSimulateFlag(autoHis);
//                }

                Thread.sleep(2L);
            }

        } catch (Exception var4) {
            log.error("err!", var4);
            throw var4;
        }
    }

    public void saveResultHis(ResultHis resultHis) throws Exception {
        try {
            resultHis.setDataId(IdGenerator.getSLId());
            StringBuffer sqlbuffer = new StringBuffer();
            sqlbuffer.append("INSERT INTO T_RESULT(DATA_ID,BUYDATE_ID,RESULT_TIME,R1,R2,R3,R4,R5,R6,R7,R8,R9,R10,INSERT_DATE,RESULT_DATE,FIRST_FLAG,FIRST_AREA,SECOND_AREA)").append(" VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
            log.debug(sqlbuffer.toString());
            this.jdbcTemplate.update(sqlbuffer.toString(), new Object[]{resultHis.getDataId(), resultHis.getBuydateId(), resultHis.getResultTime(), resultHis.getR1(), resultHis.getR2(),
                    resultHis.getR3(), resultHis.getR4(), resultHis.getR5(), resultHis.getR6(), resultHis.getR7(), resultHis.getR8(), resultHis.getR9(), resultHis.getR10(), new Date(),
                    resultHis.getResultDate(), resultHis.getFirstFlag(),resultHis.getFirstArea(),resultHis.getSecondArea()});
        } catch (Exception var3) {
            log.error("保存开奖记录失败！", var3);
            throw var3;
        }
    }

    public void saveOrUpdateResultHis(List<ResultHis> resultHisList) throws Exception {
        try {
            if(resultHisList != null && resultHisList.size() != 0) {
                Iterator var2 = resultHisList.iterator();

                while(true) {
                    ResultHis resultHis;
                    String buydateId;
                    ResultHis resultHisHis;
                    do {
                        if(!var2.hasNext()) {
                            log.info("保存数据完毕！");
                            return;
                        }

                        resultHis = (ResultHis)var2.next();
                        buydateId = resultHis.getBuydateId();
                        resultHisHis = this.queryResultHisByBuydateId(buydateId);
                    } while(resultHisHis != null && buydateId.equals(resultHisHis.getBuydateId()));

                    this.saveResultHis(resultHis);
                    Thread.sleep(2L);
                }
            } else {
                log.info("要更新开奖的数据为空");
            }
        } catch (Exception var6) {
            log.error("err!", var6);
            throw var6;
        }
    }

    public void saveAccount(Account account) throws Exception {
        try {
            account.setDataId(IdGenerator.getSLId());
            log.debug(account.toString());
            StringBuffer sqlbuffer = new StringBuffer();
            sqlbuffer.append("SELECT * FROM T_ACCOUNT WHERE ACCOUNT_ID = ?");
            log.debug(sqlbuffer.toString());
            List list = this.jdbcTemplate.queryForList(sqlbuffer.toString(), new Object[]{account.getAccountId()});
            int result;
            if(list != null && list.size() > 0) {
                log.info("account_id已存在，执行更新操作");
                sqlbuffer = new StringBuffer();
                sqlbuffer.append("UPDATE T_ACCOUNT SET DATA_ID = ?,PRE_AMOUNT = ?,INTERVAL_TIME = ? ,REMARK=? WHERE ACCOUNT_ID = ?");
                log.info(sqlbuffer.toString());
                result = this.jdbcTemplate.update(sqlbuffer.toString(), new Object[]{account.getDataId(), account.getPreAmount(), account.getIntervalTime(), account.getRemark(), account.getAccountId()});
                log.info("{} sql execute done", Integer.valueOf(result));
            } else {
                sqlbuffer = new StringBuffer();
                sqlbuffer.append("INSERT INTO T_ACCOUNT(DATA_ID,ACCOUNT_ID,PRE_AMOUNT,INTERVAL_TIME,INSERT_DATE,REMARK)").append(" VALUES(?,?,?,?,?,?)");
                log.info(sqlbuffer.toString());
                result = this.jdbcTemplate.update(sqlbuffer.toString(), new Object[]{account.getDataId(), account.getAccountId(), account.getPreAmount(), account.getIntervalTime(), account.getInsertDate(), account.getRemark()});
            }

        } catch (Exception var5) {
            log.error("err!", var5);
            throw var5;
        }
    }

    /**
     * 更新投注结果
     * @param updateList
     * @throws Exception
     */
    public void updateAutoHisByBuydateId(List<AutoHis> updateList) throws Exception {
        try {
            String buydateId = "";
            StringBuffer sqlbuffer = new StringBuffer();
            sqlbuffer.append("UPDATE T_AUTOHIS SET BUY_RESULT = ? ,BUY_MONEYTAKE = ?,BUY_RMONEYTAKE = ?,BUY_MONEYTAKE_READLY = ?,BUY_RMONEYTAKE_READLY = ?,CURR_BUYRESULT=? WHERE BUYDATE_ID = ? AND BUY_NUM = ? AND BUY_TYPE = ?");

            AutoHis autoHis;
            for(Iterator var4 = updateList.iterator(); var4.hasNext(); buydateId = autoHis.getBuydateId()) {
                autoHis = (AutoHis)var4.next();
                this.jdbcTemplate.update(sqlbuffer.toString(), new Object[]{autoHis.getBuyResult(), autoHis.getBuyMoneytake(), autoHis.getBuyRMoneytake(),autoHis.getBuyMoneyTakeReadly(),autoHis.getBuyRMoneyTakeReadly(), autoHis.getCurrBuyresult(), autoHis.getBuydateId(), autoHis.getBuyNum(), autoHis.getBuyType()});
                Thread.sleep(2L);
            }

            log.info("{}期下注结果更新完毕！", buydateId);
        } catch (Exception var6) {
            log.error("更新投注结果失败！", var6);
            throw var6;
        }
    }

    /**
     * 清除穿版
     * @throws Exception
     */
    public void clearDieCount() throws Exception {
        try {

            StringBuffer sqlbuffer = new StringBuffer();
            sqlbuffer.append("UPDATE T_AUTOHIS SET DIE_COUNT_READLY = 0");
            this.jdbcTemplate.update(sqlbuffer.toString());

            log.info("穿版数量清空完毕！");
        } catch (Exception var6) {
            log.error("穿版数量清空失败！", var6);
            throw var6;
        }
    }

    /**
     * 更新投注初始数据
     * @param autoHis
     * @throws Exception
     */
    public void updateSimulateFlag( AutoHis autoHis ) throws Exception {
        try {

            StringBuffer sqlbuffer = new StringBuffer();
            sqlbuffer.append("UPDATE T_AUTOHIS SET FIRST_FLAG = ? , BUY_AMOUNT = ? ,  BUY_RESULT = ? ,  BUY_MONEYTAKE = ? , " +
                    " INSERT_DATE = ? ,  BET_RULE = ? ,  BUY_WHAT = ? ,  BUY_RMONEYTAKE = ? ,  CURR_BUYRESULT = ? , " +
                    " LAST_BUYRESULT = ? ,  SIMULATE_FLAG = ? ,  PRE_AMOUNT = ? ,  DIE_COUNT = 0     where BUYDATE_ID  = ? and BUY_TYPE = ? BUY_NUM = ? ");
            this.jdbcTemplate.update(sqlbuffer.toString() , new Object[]{ autoHis.getFirstFlag(),autoHis.getBuyAmount(),autoHis.getBuyResult(),
                    autoHis.getBuyMoneytake(),new Date(),autoHis.getBetRule(),autoHis.getBuyWhat(),autoHis.getBuyRMoneytake(),
                    autoHis.getCurrBuyresult(),autoHis.getLastBuyresult(),autoHis.getSimulateFlag(),autoHis.getPreAmount(),
                    autoHis.getPreAmount(),autoHis.getDieCount(),autoHis.getBuydateId(),autoHis.getBuyType(),autoHis.getBuyNum()});

            log.info("还原模拟！");
        } catch (Exception var6) {
            log.error("还原模拟！", var6);
            throw var6;
        }
    }


    /**
     * 更新统计
     * @param betType
     * @param betNum
     * @param buyDateID
     * @throws Exception
     */
    public void setTakeMoneySum( BigDecimal sum , String betType,String betNum,String buyDateID ) throws Exception {
        try {

            StringBuffer sqlbuffer = new StringBuffer();
            sqlbuffer.append("UPDATE T_AUTOHIS SET sum_moneytake = ? where BUY_TYPE = ? AND BUY_NUM = ? AND BUYDATE_ID  = ? ");
            this.jdbcTemplate.update(sqlbuffer.toString() , new Object[]{ sum , betType , betNum , buyDateID});

            log.info("统计完成！");
        } catch (Exception var6) {
            log.error("统计失败！", var6);
            throw var6;
        }
    }

    /**
     * 可视化数据每期盈亏
     * @return
     * @throws Exception
     */
    public List<Visualization> queryVisualizationData() throws Exception {
        try {
            StringBuffer sqlbuffer = new StringBuffer();
            sqlbuffer.append("SELECT BUYDATE_ID , sum(buy_moneytake) buy_moneytake FROM T_AUTOHIS where readly_flag = 'true' GROUP BY BUYDATE_ID ORDER BY BUYDATE_ID ");

            List<Visualization>  visualizationList = this.jdbcTemplate.query(sqlbuffer.toString() ,new BeanPropertyRowMapper(Visualization.class));
            return visualizationList;
        } catch (Exception var4) {
            log.error("err!", var4);
            return null;
        }
    }

    /**
     * 可视化数据每期盈亏统计
     * @return
     * @throws Exception
     */
    public List<Visualization> queryVisualizationDataSum() throws Exception {
        try {
            StringBuffer sqlbuffer = new StringBuffer();
            sqlbuffer.append("SELECT BUYDATE_ID , sum(sum_moneytake) buy_moneytake FROM T_AUTOHIS where  sum_moneytake is not  NULL GROUP BY BUYDATE_ID ORDER BY BUYDATE_ID ");

            List<Visualization>  visualizationList = this.jdbcTemplate.query(sqlbuffer.toString() ,new BeanPropertyRowMapper(Visualization.class));
            return visualizationList;
        } catch (Exception var4) {
            log.error("err!", var4);
            return null;
        }
    }

    /**
     *
     * @throws Exception
     */
    public void setCarData( String type , String NO , String dieCount) throws Exception {
        try {

            Boolean updateFlag = false;
            Object[] parm = new Object[4];
            StringBuffer sqlbuffer = new StringBuffer();
            sqlbuffer.append("UPDATE T_AUTOHIS SET ");
            int index = 0;
            if ( dieCount != null && !"".equals(dieCount)){
                int typeInt =  Integer.parseInt(dieCount);

                if( typeInt > 0 ){
                    sqlbuffer.append("DIE_COUNT_READLY = ? ");
                    parm[index] = typeInt;
                    updateFlag = true;
                    index = index+ 1 ;
                }

            }

            sqlbuffer.append(" WHERE BUY_TYPE = ?  AND BUY_NUM = ?  ");

            if(updateFlag ){

                parm[index] = type;
                parm[index+ 1] = NO;
                this.jdbcTemplate.update(sqlbuffer.toString() , new Object[]{ dieCount , type , NO });
            }


            log.info("穿版数量清空完毕！");
        } catch (Exception var6) {
            log.error("穿版数量清空失败！", var6);
            throw var6;
        }
    }

    /**
     * 更新选择结果
     * @param resultHis
     * @throws Exception
     */
    public void updateResultHisByBuydateId(ResultHis resultHis) throws Exception {
        try {
            String buydateId = "";
            StringBuffer sqlbuffer = new StringBuffer();
            sqlbuffer.append("UPDATE T_RESULT SET FIRST_SELECT = ? ,SECOND_SELECT = ? WHERE BUYDATE_ID = ? ");
            this.jdbcTemplate.update(sqlbuffer.toString(), new Object[]{resultHis.getFirstSelect(),resultHis.getSecondSelect(),resultHis.getBuydateId()});

            log.info("{}期下注结果更新完毕！", buydateId);
        } catch (Exception var6) {
            log.error("更新投注结果失败！", var6);
            throw var6;
        }
    }

    /**
     * 查询计算结果
     * @return
     * @throws Exception
     */
    public List<ResultHis> queryResultHis() throws Exception {
        try {
            StringBuffer sqlbuffer = new StringBuffer();
            sqlbuffer.append("select * from T_RESULT order by buydate_id desc");
            log.debug(sqlbuffer.toString());
            List<ResultHis> list = this.jdbcTemplate.query(sqlbuffer.toString(), new BeanPropertyRowMapper(ResultHis.class));
            return list;
        } catch (Exception var4) {
            log.error("queryAutoHisTop err!", var4);
            throw var4;
        }
    }

    /**
     * 建表
     * @throws Exception
     */
    public void createTable() throws Exception {
        try {
            log.info("开始建表");
            String excuteSql = "drop table t_account if exists";
            log.info(excuteSql);
            this.jdbcTemplate.execute(excuteSql);
            excuteSql = "drop table t_autohis if exists";
            log.info(excuteSql);
            this.jdbcTemplate.execute(excuteSql);
            excuteSql = "drop table t_result if exists";
            log.info(excuteSql);
            this.jdbcTemplate.execute(excuteSql);
            excuteSql = "CREATE TABLE t_account(id SERIAL, data_id VARCHAR(255) , account_id VARCHAR(255),pre_amount VARCHAR(255),interval_time varchar(255),insert_date datetime,remark VARCHAR(255) )";
            log.info(excuteSql);
            this.jdbcTemplate.execute(excuteSql);
            //下注结果表
            excuteSql = "CREATE TABLE t_autohis(id SERIAL, data_id VARCHAR(255) , account_id VARCHAR(255),buydate_id VARCHAR(255),first_flag VARCHAR(255),buy_num VARCHAR(255),buy_type VARCHAR(255),buy_amount int,buy_result VARCHAR(255),buy_moneytake DECIMAL(10,2),insert_date datetime,remark VARCHAR(255),bet_rule VARCHAR(255),buy_what VARCHAR(255),buy_rmoneytake DECIMAL(10,2),curr_buyresult VARCHAR(255),last_buyresult VARCHAR(255),simulate_flag VARCHAR(255),pre_amount int,die_count int ,readly_flag VARCHAR(255),buy_amount_readly int,buy_moneytake_readly DECIMAL(100,2),buy_what_readly VARCHAR(255),buy_rmoneytake_readly DECIMAL(100,2),pre_amount_readly int,die_count_readly int,sum_moneytake DECIMAL(100,2))";
            log.info(excuteSql);
            this.jdbcTemplate.execute(excuteSql);
            excuteSql = "CREATE TABLE t_result(id SERIAL, data_id VARCHAR(255) , buydate_id VARCHAR(255),result_time VARCHAR(255),r1 VARCHAR(255),r2 VARCHAR(255),r3 VARCHAR(255),r4 VARCHAR(255),r5 VARCHAR(255),r6 VARCHAR(255),r7 VARCHAR(255),r8 VARCHAR(255),r9 VARCHAR(255),r10 VARCHAR(255),first_flag VARCHAR (255),insert_date datetime,result_date VARCHAR(255) ,first_area VARCHAR (255),second_area VARCHAR (255),first_select VARCHAR (255),second_select VARCHAR (255))";
            log.info(excuteSql);
            this.jdbcTemplate.execute(excuteSql);
            log.info("建表完毕");
        } catch (Exception var2) {
            log.error("err!", var2);
            throw var2;
        }
    }

    /**
     * 不建表，删除数据
     * @throws Exception
     */
    public void deleteTableData() throws Exception {
        try {
            log.info("开始删除数据");
            String excuteSql = "DELETE t_account";
            log.info(excuteSql);
            this.jdbcTemplate.execute(excuteSql);
            excuteSql = "DELETE t_result";
            log.info(excuteSql);
            this.jdbcTemplate.execute(excuteSql);
            log.info("建表完毕");
        } catch (Exception var2) {
            log.error("err!", var2);
            throw var2;
        }
    }
}
